package com.duoec.dw.lineage.service.analyser.group;

import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;

/**
 * @author xuwenzhen
 */
@Service
public class SelectGroupByClauseAnalyser extends BaseGroupByAnalyser<SQLSelectGroupByClause> {
    /**
     * 获取当前类处理的类型
     *
     * @return SQLSelectGroupByClause类型
     */
    @Override
    public Class<SQLSelectGroupByClause> getType() {
        return SQLSelectGroupByClause.class;
    }

    /**
     * 解析 group by
     *
     * @param groupBy           group by语句
     * @param fromTableLineages from解析出来的多个血缘关系数据
     * @param tableLineage      当前语句的血缘关系数据
     * @return 解析此表达式可抽取的字段依赖
     */
    @Override
    public void analyse(SQLSelectGroupByClause groupBy, MultiTableLineageDto fromTableLineages, TableLineageDto tableLineage) {
        LinkedHashSet<TableFieldDependencyDto> dependencies = new LinkedHashSet<>();
        groupBy.getItems().forEach(item -> {
            LinkedHashSet<TableFieldDependencyDto> dependencies1 = hiveAnalyser.analyseExpr(fromTableLineages, item);
            AnalyserUtils.mergeToDependencies(dependencies, dependencies1);
        });
        LinkedHashSet<TableFieldDependencyDto> dependencies2 = hiveAnalyser.analyseExpr(fromTableLineages, groupBy.getHaving());
        AnalyserUtils.mergeToDependencies(dependencies, dependencies2);
        tableLineage.getDependencies().addAll(dependencies);
    }
}
